package just.stuff.morsels.ui.assist;

import just.stuff.morsels.MorselApplication;
import just.stuff.morsels.MorselSession;
import just.stuff.morsels.objects.User;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.model.Model;

public class OfferAssistanceLink extends AjaxLink<String> {

	private String label;
	
	public OfferAssistanceLink( String id, final String label ) {
		super( id, new Model<String>() {
			@Override
			public String getObject() {
				User user = MorselSession.get().getUser();
				return ( user != null && user.isAssistanceSubscribed( label ) ) ? "Withdraw assistance" : "Offer assistance";
			}
		});
		this.label = label;
		setOutputMarkupPlaceholderTag( true );
	}
	
	@Override
	public void onClick(AjaxRequestTarget target) {
		User user = MorselSession.get().getUser();
		user.toggleAssistanceSubscription( label );
		MorselApplication.dataSource().save( user );
		
		target.addComponent( this );
	}
	
	@Override
	public boolean isVisible() {
		return MorselSession.isSignedIn();
	}
	
	public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
		replaceComponentTagBody(markupStream, openTag, getModelObject() );
	}
		
	
	
}
